package cn.gok.listener;

import cn.gok.pojo.Examination;
import cn.gok.pojo.Excels;
import cn.gok.pojo.ExcelsPro;
import cn.gok.service.AdminService;
import cn.gok.service.ExcelsService;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.data.ReadCellData;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExcelListener extends AnalysisEventListener<Excels> {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExcelListener.class);

    private static final int BATCH_COUNT = 10;
    //    private final ExcelsService excelService;
    // 记录Excel读取的行数
    private int COUNT = 0;

    // 记录Excel重复的行数
    private int duplicateCOUNT = 0;
    private String title;

    //保存读取成功的Excel数据
    private List<ExcelsPro> data = new ArrayList<>();
    //保存查询出来的表头
    private List<Examination> examinationList = new ArrayList<>();
    //保存读取成功的databases数据
    private List<Examination> databasesList = new ArrayList<>();
    //用于存放表头
    private Map<String, String> map = new HashMap<>();
    //保存读取失败的Excel消息
    private List<String> errorMessage = new ArrayList<>();
    //service
    private ExcelsService excelsService;

    public ExcelListener() {
    }

    //初始化监听器
    public ExcelListener(ExcelsService excelsService) {

        this.excelsService = excelsService;
    }

    //    private void calcuateMealTimes(Excels excels) {
//    }
    //每条数据都会被调用
    @Override
    public void invoke(Excels excels, AnalysisContext analysisContext) {
        ExcelsPro excelsPro = new ExcelsPro();
        excelsPro.setExcels(excels);
        //将标题设置成默认值
        excelsPro.setTitle(map.get("title"));
        System.out.println(excelsPro);
        data.add(excelsPro);
//        list.add(excels1);

        //每次读取10条数据就进行保存操作,清理list ，方便内存回收
        if (data.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            data.clear();
        }

    }

    /**
     * 重写invokeHeadMap方法，获去表头，如果有需要获取第一行表头就重写这个方法，不需要则不需要重写
     *
     * @param headMap Excel每行解析的数据为Map<Integer, String>类型，Integer是Excel的列索引,String为Excel的单元格值
     * @param context context能获取一些东西，比如context.readRowHolder().getRowIndex()为Excel的行索引，表头的行索引为0，0之后的都解析成数据
     */
    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {

        if ((context.readRowHolder().getRowIndex() == 0)) {
            //表头
            map.put("title", headMap.get(0).getStringValue());
        } else if (context.readRowHolder().getRowIndex() == 1) {
            //数据库链接数据
            //因为port数据传过来是数字类型，要用getNumberValue()接收，再用intValue()强转成int类型，将接收的数据除去小数点，然后再用String.valueOf()强转成String类型
            map.put("ip", headMap.get(0).getStringValue());
            map.put("ports", String.valueOf((headMap.get(1).getNumberValue()).intValue()));
            map.put("databases", headMap.get(2).getStringValue());
            map.put("username", headMap.get(3).getStringValue());
            map.put("password", headMap.get(4).getStringValue());
            System.out.println(map);
            Examination databases = new Examination();
            databases.setIp(map.get("ip"));
            databases.setTitle(map.get("title"));
            databases.setPorts(map.get("ports"));
            databases.setUsername(map.get("username"));
            databases.setPassword(map.get("password"));
            databases.setDatabases(map.get("databases"));
            databasesList.add(databases);
            /*设置总和sum，用examinationList接收查询的题库数据，再用for循环将标题提取出来，与前端接收的标题进行对比，倘如相等则sum+1,
            跳过表头插入到数据库，否则就执行saveData方法，将数据插入到数据库中
            */
            int sum=0;
            List<Examination> examinationList = excelsService.sel();
            for (Examination examination : examinationList) {
                if (databases.getTitle().equals(examination.getTitle())) {
                    sum++;
                }
            }
            if (sum == 1) {
                System.out.println(123);
            } else {
                System.out.println(databases.getTitle());
                excelsService.saveData(databasesList);
            }
//
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
    }

    private void saveData() {
        System.out.println(data.size() + "条数据，开始存储数据库！");
        //保存数据
        System.out.println(data);
        excelsService.save(data);
    }
}
